<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\api\logic;

use app\common\logic\LogicBase;
use app\api\error\CodeBase;

/**
 * Api基础逻辑
 */
class ApiBase extends LogicBase
{

    /**
     * API返回数据
     */
    public function apiReturn($code_data = [], $return_data = 0, $return_type = 'json')
    {
        
        if (is_array($code_data) && array_key_exists(API_CODE_NAME, $code_data)) {
            //!empty($return_data) && $code_data['data'] = $return_data;
            $result = $code_data;
            
        } else {
            $result = CodeBase::$success;
            $result['data'] = $code_data;
        }
        //临时页码
        !empty($return_data) && $result['page']=$return_data;

        $return_result = $this->checkDataSign($result);
        
        $return_result['exe_time'] = debug('api_begin', 'api_end');
        
        return $return_type == 'json' ? json($return_result) : $return_result;
    }

    /**
     * 检查是否需要响应数据签名
     */
    public function checkDataSign($data)
    {
        
        $info = $this->modelApi->getInfo(['api_url' => URL]);
        
        $info['is_response_sign'] && !empty($data['data']) && $data['data']['data_sign'] = create_sign_filter($data['data']);
        
        return $data;
    }
    
    /**
     * API错误终止程序
     */
    public function apiError($code_data = [])
    {
        
        return throw_response_exception($code_data);
    }

    /**
     * API提交附加参数检查
     */
    public function checkParam($param = [])
    {
		if( URL != 'common/getapikey'){
			$info = $this->modelApi->getInfo(['api_url' => URL]);
        
			empty($info) && $this->apiError(CodeBase::$apiUrlError);
			
			//(empty($param['access_token']) || $param['access_token'] != get_access_token()) && $this->apiError(CodeBase::$accessTokenError);
			
			if ($info['is_user_token'] && empty($param['user_token'])) {
				
				$this->apiError(CodeBase::$userTokenNull);
				
			} elseif ($info['is_user_token']) {
			
				$decoded_user_token = decoded_user_token($param['user_token']);
				is_string($decoded_user_token) && $this->apiError(CodeBase::$userTokenError);
				$timeout=db('user')->where('token',$param['user_token'])->value('timeout');
				if(empty($timeout)){
					$this->apiError(CodeBase::$userTokenError);
				}else{
					if(time()-$timeout > 15*24*60*60){
						$this->apiError(CodeBase::$TokenTimeError);
					}
				}
				//var_dump($decoded_user_token);exit;
                $pinfo=$decoded_user_token['data'];
                $info['is_request_sign'] && ($pinfo->user_id != $param['user_id']) && $this->apiError(CodeBase::$dataSignError);
			}
			//$info['is_request_sign']    && (empty($param['data_sign'])      || create_sign_filter($param) != $param['data_sign']) && $this->apiError(CodeBase::$dataSignError);
		}       
    }
    /**
     *
     * 生成缓存
     * @param $key str 文件名（不包含后缀）
     * @param $value array 数据
     * @param $path str 路径
     * return string
     *
     */
    Public function cacheData($key,$value='',$cacheTime=0){
        $root = $_SERVER['DOCUMENT_ROOT'].'/Data/';
        $filename=$root.$key.'.txt';
        if($value !== ''){//将value值写入缓存
            if(is_null($value)){
                return @unlink($filename);//删除文件
            }
            $dir = dirname($filename);
            if(!is_dir($dir)){
                mkdir($dir,0777);//创建文件夹
            }
            $cacheTime=sprintf('%011d',$cacheTime);//设置缓存失效时间，11位，不满11位用0填充
            return file_put_contents($filename,$cacheTime.json_encode($value));//成功返回字节数，否则返回false
        }
        if(!is_file($filename)){
            return false;
        }
        $contents = file_get_contents($filename);//读取用户
        $cacheTime = (int)substr($contents,0,11);
        $value = substr($contents,11);
        if($cacheTime !=0 && $cacheTime + filemtime($filename) < time()){
            @unlink($filename);
            return false;
        }
        return json_decode($value,true);
    }

}
